(*
  https://www.rfc-editor.org/rfc/rfc9421#appendix-B
*)
open Alcotest

module AS = struct
  open Angstrom
  let tc_int () =
    let p_integer = take_while1 Astring.Char.Ascii.is_digit >>| int_of_string in
    let n_integer = char '-' *> p_integer >>| Int.neg in
    let sf_integer = p_integer <|> n_integer in
    "23" |> parse_string ~consume:All sf_integer |> Result.get_ok |> check int __LOC__ 23;
    "-12" |> parse_string ~consume:All sf_integer |> Result.get_ok |> check int __LOC__ (-12)
  let tc_unesc () =
    let none = satisfy (fun _ -> false) in
    let _DQUOTE = char '"' in
    let _PERCENT = char '%' in
    let _alph = String.fold_left (fun a c -> a <|> char c) none in
    let crange c0 c1 =
      let r = ref none in
      for c = c0 to c1 do
        r := !r <|> char (Char.chr c)
      done ;
      !r
    in
    let unescaped = crange 0x20 0x21 <|> crange 0x23 0x24 <|> crange 0x26 0x58 <|> crange 0x5D 0x7E in
    let bs_escaped = unescaped in
    let cl2s cl = let b = Bytes.make (cl |> List.length) '_' in
      let _ = cl |> List.fold_left (fun i c ->
          Bytes.set b i c;
          (succ i)) 0 in
      b |> Bytes.to_string in
    let sf_string = _DQUOTE *> many (unescaped <|> _PERCENT <|> bs_escaped) >>| cl2s <* _DQUOTE in
    {|"uhulol"|} |> parse_string ~consume:All sf_string |> Result.get_ok |> check Alcotest.string __LOC__ "uhulol"

end

let set_up () =
  Mirage_crypto_rng_unix.use_default ();
  Unix.chdir "../../../test/"

let () =
  run
    "seppo_suite" [
    __FILE__ , [
      "set_up",              `Quick, set_up;
      "AS.tc_int",           `Quick, AS.tc_int;
      "AS.tc_unesc",         `Quick, AS.tc_unesc;
      (* "AS.tc_rfc9561",       `Quick, AS.tc_rfc9561; *)
    ]
  ]
